package imsdk

import (
	"encoding/json"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/http"
)

type (
	OperationTag struct {
		UserTags []UserTags `json:"UserTags"`
	}

	UserTags struct {
		ToAccount string   `json:"To_Account,omitempty"`
		Tags      []string `json:"Tags,omitempty"`
	}
)

//每次请求最多只能给100个用户添加标签，请求体中单个用户添加标签数最多为10个。
//单个用户可设置最大标签数为100个，若用户当前标签超过100，则添加新标签之前请先删除旧标签。
//单个标签最大长度为50字节。

// add tags
func (s sdk) AddTags(users, tags []string) {
	url := GetSdk().BuildRestfulUrl("/all_member_push/im_add_tag")

	var o OperationTag
	for _, user := range users {
		o.UserTags = append(o.UserTags, UserTags{
			ToAccount: user,
			Tags:      tags,
		})
	}

	j, err := json.Marshal(o)
	if err != nil {
		global.Log.Errorf("AddTags Marshal error: %v", err)
		return
	}

	global.Log.Infof("AddTags: %s", string(j))
	result, err := http.HttpPost(url, string(j), connTimeoutMs, serveTimeoutMs, "application/json")
	if err != nil {
		global.Log.Errorf("Broadcast AddTags http request error: %v, result: %o", err, string(result))
		return
	}
	global.Log.Debugf("Broadcast AddTags result: %o", string(result))
	return
}

// delete tags
func (s sdk) DeleteTags(users, tags []string) {
	url := GetSdk().BuildRestfulUrl("/all_member_push/im_remove_tag")

	var o OperationTag
	for _, user := range users {
		o.UserTags = append(o.UserTags, UserTags{
			ToAccount: user,
			Tags:      tags,
		})
	}

	j, err := json.Marshal(o)
	if err != nil {
		global.Log.Errorf("DeleteTags Marshal error: %v", err)
		return
	}

	global.Log.Infof("DeleteTags: %s", string(j))
	result, err := http.HttpPost(url, string(j), connTimeoutMs, serveTimeoutMs, "application/json")
	if err != nil {
		global.Log.Errorf("Broadcast DeleteTags http request error: %v, result: %o", err, string(result))
		return
	}
	global.Log.Debugf("Broadcast DeleteTags result: %o", string(result))
	return
}
